package com.znsd.zl.house.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.znsd.zl.utils.PageUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @ClassName ConditionPageUtils
 * @Description TODO
 * @Author zhubin
 * @Date 2020/8/18 9:50
 * @Version v1.0
 */
@SuppressWarnings("all")
public class ConditionPageUtils {

	/**
	 *  动态进行条件查询
	 * @param condition 封装的查询参数
	 * @param baseMapper 执行的dao对象
	 * @return 查询的分页对象
	 */
	public static PageUtils conditionPage(Map<String,Object> condition, BaseMapper baseMapper){
		Object current = condition.remove("page");
		Object size = condition.remove("limit");
		// 默认分页
		Integer page = 1;
		Integer limit = 10;
		if (current != null) {
			page = Integer.parseInt(current.toString());
		}
		if (size != null) {
			limit = Integer.parseInt(size.toString());
		}
		// 多条件查询封装
		QueryWrapper qw = new QueryWrapper<>();
		//循环封装条件
		for (String key : condition.keySet()) {
			Object value =  condition.get(key);
			if ("t".equals(key)) { continue; }
			qw.eq(!StringUtils.isEmpty(value),key,value);
		}
		IPage iPage = baseMapper.selectPage(new Page<>(page, limit), qw);
		return new PageUtils(iPage);
	}

	/**
	 *  对分页数据进行封装
	 * @param startNum 当前页数
	 * @param size     展示总数
	 * @param data     当前数据
	 * @param count    所有查询数据
	 * @return
	 */
	public static PageUtils pageData(Integer startNum, Integer size, List data, Integer count) {
		PageUtils pageUtils = new PageUtils();
		// 保存分页所有参数
		pageUtils.setCurrPage(startNum);
		pageUtils.setPageSize(size);
		pageUtils.setList(data);
		pageUtils.setTotalCount(count);
		Integer totalPage = count % size == 0 ? count / size : (count / size) + 1;
		pageUtils.setTotalPage(totalPage);
		return pageUtils;
	}

	/**
	 *  解析map中的分页数据
	 * @param params 封装的数据集合
	 * @return  返回page 和 limit
	 */
	public static int[] getPageAndLimit(Map<String,Object> params){
		Object current = params.remove("page");
		Object size = params.remove("limit");
		// 删除t
		params.remove("t");
		// 默认1 和 10
		Integer page = 1;
		Integer limit = 10;
		// 获取用户传入分页
		if (current != null) {
			page = Integer.parseInt(current.toString());
		}
		if (size != null) {
			limit = Integer.parseInt(size.toString());
		}
		int[] savePage = new int[2];
		savePage[0] = page;
		savePage[1] = limit;
		return savePage;
	}

}
